<template>
  <div class="home">
    <div class="box">
      <div class="top">
        <div class="left">
          <div class="dot">
            <img src="/images/home/dot.svg" alt="" />
          </div>
          <div class="header" @dblclick="goToAdmin">{{ customTitle }}</div>
          <div class="hot">
            <div class="header">
              <img src="/images/home/hot.svg" alt="" />
            </div>
            <div class="tab-list">
              <div
                class="tab"
                v-for="(item, index) in settings.hotSections || []"
                :key="index"
                @click="handleHotClick(item)"
              >
                <img
                  :src="item.imageUrl ? handleProxy(item.imageUrl) : ''"
                  :alt="item.targetValue || ''"
                  @error="$event.target.style.display = 'none'"
                />
              </div>
              <div class="tab" @click="$router.push('/notice')">
                <img src="/images/home/note.png" alt="" />
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <img class="banner" :src="getBannerUrl()" alt="" v-if="getBannerUrl()" />
          <!-- 通知栏 -->
          <div class="notice-bar" @click="handleNoticeClick()">
            <img class="notice-icon" src="/images/home/notice-icon.svg" alt="" />
            <div class="notice-content" ref="noticeContentRef">
              <div
                class="notice-text"
                :class="{ 'scroll-animation': shouldScroll }"
                ref="noticeTextRef"
              >
                {{ currentNotice?.noticeTitle || '暂无通知' }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 顶级服务菜单 -->
      <div class="service">
        <div class="header">
          <img src="/images/home/service.svg" alt="" />
        </div>
        <div class="service-list">
          <div
            class="item"
            v-for="menu in topMenus"
            :key="menu.id || menu.name"
            :style="{
              backgroundImage: menu.homeImage ? `url(${handleProxy(menu.homeImage)})` : 'none',
            }"
            @click="handleServiceClick(menu)"
          ></div>
        </div>
      </div>
      <!-- 地图点位分类 -->
      <div class="map">
        <div class="header">
          <img src="/images/home/map.svg" alt="" />
        </div>
        <div class="map-list">
          <div
            class="item"
            v-for="category in categories"
            :key="category.id || category.name"
            :style="{
              backgroundImage: category.homeImage
                ? `url(${handleProxy(category.homeImage)})`
                : 'none',
            }"
            @click="handleMapClick(category)"
          ></div>
        </div>
      </div>
    </div>
    <div class="footer">台州市椒江区人力资源和社会保障局</div>
  </div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import {
  getSettings,
  getCategoryList,
  getNoticeBanner,
  getTopMenu,
  handleProxy,
  getNoticeDetail,
} from '@/api/data.js'
import { useRouter } from 'vue-router'
import {
  getCustomTitle,
  getCustomBanner,
  getCustomServiceOrder,
  getCustomCategoryOrder,
  resetOutdatedConfig,
} from '@/utils/customStorage.js'

// 响应式数据
const settings = ref({
  title: '青椒人社通',
  bannerUrl: '',
  hotSections: [],
})
const topMenus = ref([])
const categories = ref([])
const customTitle = ref('椒江区人才社区地图')
const customBanner = ref('')
const originalServices = ref([])
const originalCategories = ref([])
const isLoading = ref(true)
const loadError = ref(null)
const router = useRouter()

// 通知相关
const noticeList = ref([])
const currentNoticeIndex = ref(0)
const noticeTimer = ref(null)
const noticeContentRef = ref(null)
const noticeTextRef = ref(null)
const shouldScroll = ref(false)

// 当前通知
const currentNotice = computed(() => {
  if (noticeList.value.length === 0) return null
  return noticeList.value[currentNoticeIndex.value]
})
// 获取首页设置
const fetchSettings = async () => {
  try {
    const res = await getSettings()
    if (res && res.data && res.data.code === 200 && res.data.data) {
      // 确保hotSections是数组
      const data = res.data.data
      settings.value = {
        title: data.title || '青椒人社通',
        bannerUrl: data.bannerUrl || '',
        hotSections: Array.isArray(data.hotSections) ? data.hotSections : [],
      }
    }
  } catch (error) {
    console.error('获取首页设置失败:', error)
    // 保持默认值，不抛出错误
  }
}

// 获取顶级菜单
const fetchTopMenus = async () => {
  try {
    const res = await getTopMenu()
    if (res && res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      originalServices.value = res.data.data
      topMenus.value = getCustomServiceOrder(originalServices.value)
    }
  } catch (error) {
    console.error('获取顶级菜单失败:', error)
    // 保持空数组，不抛出错误
    originalServices.value = []
    topMenus.value = []
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res && res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      originalCategories.value = res.data.data
      categories.value = getCustomCategoryOrder(originalCategories.value)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 保持空数组，不抛出错误
    originalCategories.value = []
    categories.value = []
  }
}

// 检查数据更新（在所有数据加载完成后调用）
const checkAndResetConfig = () => {
  if (originalServices.value.length > 0 && originalCategories.value.length > 0) {
    resetOutdatedConfig(originalServices.value, originalCategories.value)
  }
}

// 热门区域点击事件
const handleHotClick = (item) => {
  console.log('热门区域点击:', item)
  // 根据targetType和targetValue进行路由跳转
  if (item.targetType === 'service') {
    router.push({
      path: `/service`,
      query: { name: item.targetValue },
    })
  }
}

// 服务项目点击事件
const handleServiceClick = (menu) => {
  console.log('服务项目点击:', menu)
  router.push({
    path: `/service`,
    query: { id: menu.id },
  })
}

// 地图分类点击事件
const handleMapClick = (category) => {
  console.log('地图分类点击:', category)
  router.push({
    path: `/source`,
    query: { id: category.id },
  })
}

// 进入管理页面（双击标题触发）
const goToAdmin = () => {
  router.push('/admin')
}

// 获取通知列表
const fetchNoticeList = async () => {
  try {
    const res = await getNoticeBanner()
    console.log('通知列表原始数据:', res.data.data)
    if (res && res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      // 显示所有通知，如果需要只显示启用的，改为 item.status === 1
      noticeList.value = res.data.data
      console.log('通知列表:', noticeList.value)
      console.log('通知列表数量:', noticeList.value.length)
      if (noticeList.value.length > 0) {
        startNoticeRotation()
      }
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    noticeList.value = []
  }
}

// 检查文字是否需要滚动
const checkTextOverflow = async () => {
  await nextTick()
  if (noticeContentRef.value && noticeTextRef.value) {
    const contentWidth = noticeContentRef.value.offsetWidth
    const textWidth = noticeTextRef.value.scrollWidth
    shouldScroll.value = textWidth > contentWidth
  }
}

// 开始通知轮播
const startNoticeRotation = () => {
  stopNoticeRotation()
  checkTextOverflow()

  console.log('启动通知轮播，通知数量:', noticeList.value.length)
  
  // 只有当通知数量大于1时才启动定时器
  if (noticeList.value.length > 1) {
    noticeTimer.value = setInterval(() => {
      currentNoticeIndex.value = (currentNoticeIndex.value + 1) % noticeList.value.length
      console.log('切换到通知索引:', currentNoticeIndex.value, '通知标题:', currentNotice.value?.noticeTitle)
      shouldScroll.value = false
      checkTextOverflow()
    }, 5000) // 每5秒切换
    console.log('定时器已启动，ID:', noticeTimer.value)
  } else {
    console.log('只有一条或没有通知，不启动轮播')
  }
}

// 停止通知轮播
const stopNoticeRotation = () => {
  if (noticeTimer.value) {
    clearInterval(noticeTimer.value)
    noticeTimer.value = null
  }
}

// 处理通知跳转
const handleNoticeClick = async () => {
  if (!currentNotice.value) return

  const notice = currentNotice.value
  if (notice.noticeType === 'link' && notice.noticeLink) {
    // 外链类型，打开新窗口
    window.open(notice.noticeLink, '_blank')
  } else if (notice.noticeType === 'manual' && notice.noticeId) {
    // 手动录入类型，跳转到详情页
    router.push({
      path: '/notice',
      query: { id: notice.noticeId },
    })
  }
}

// 获取Banner URL（优先使用自定义Banner，否则使用设置中的Banner）
const getBannerUrl = () => {
  const custom = customBanner.value
  const default_ = settings.value.bannerUrl

  // 如果有自定义Banner
  if (custom) {
    // 如果是BASE64格式，直接返回
    if (custom.startsWith('data:image/')) {
      return custom
    }
    // 如果是URL，通过handleProxy处理
    return handleProxy(custom)
  }

  // 使用默认Banner
  return default_ ? handleProxy(default_) : ''
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    isLoading.value = true
    loadError.value = null

    // 获取自定义标题和Banner（同步操作，有默认值保护）
    try {
      customTitle.value = getCustomTitle()
      customBanner.value = getCustomBanner()
    } catch (storageError) {
      console.warn('读取本地配置失败，使用默认值:', storageError)
      customTitle.value = '椒江区人才社区地图'
      customBanner.value = ''
    }

    // 并行获取数据，即使某个失败也不影响其他
    const results = await Promise.allSettled([
      fetchSettings(),
      fetchTopMenus(),
      fetchCategories(),
      fetchNoticeList(),
    ])

    // 检查失败的请求
    let hasError = false
    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        const apiNames = ['设置', '顶级菜单', '分类列表', '通知列表']
        console.error(`获取${apiNames[index]}失败:`, result.reason)
        hasError = true
      }
    })

    // 在所有数据加载完成后检查数据更新
    try {
      checkAndResetConfig()
    } catch (configError) {
      console.warn('检查配置更新失败:', configError)
    }

    // 设置加载错误状态（如果有的话）
    if (hasError) {
      loadError.value = '部分数据加载失败，页面可能显示不完整'
    }
  } catch (error) {
    console.error('页面初始化失败:', error)
    loadError.value = '页面初始化失败，请刷新重试'
  } finally {
    isLoading.value = false
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopNoticeRotation()
})
</script>
<style scoped lang="scss">
.home {
  background: url('/images/home/bg.png') no-repeat center top;
  background-repeat: no-repeat;
  background-size: cover;
  width: 1920px;
  height: 100vh;
  position: relative;
  .box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 1368px;
    height: 642px;
    transform: translate(-50%, -50%);
    border-radius: 24px;
    border: 2px solid #fff;
    background: #ffffff80;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 24px;
    .top {
      display: flex;
      justify-content: space-between;
      gap: 20px;
      .left {
        width: 652px;
        height: 296px;
        border-radius: 8px;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .dot {
          position: absolute;
          right: 0;
          top: 0;
          width: 180px;
          height: 91px;
          transform: rotateY(180deg);
          opacity: 0.6;
          border-top-left-radius: 8px;
        }
        .header {
          font-family: YouSheBiaoTiHei;
          font-weight: 400;
          font-style: italic;
          font-size: 48px;
          background: linear-gradient(90deg, #2f403e 0%, #506d6a 100%);
          background-clip: text;
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
        .hot {
          .header {
            width: 111px;
            height: 32px;
            margin-bottom: 28px;
          }
          .tab-list {
            display: flex;
            gap: 17px;
          }
          .tab {
            cursor: pointer;
            width: 150px;
            height: 162px;
            border-top-left-radius: 8px;
            border-top-right-radius: 20px;
            border-bottom-right-radius: 8px;
            border-bottom-left-radius: 8px;
          }
        }
      }
      .right {
        width: 656px;
        height: 250px;
        position: relative;
        .banner {
          width: 100%;
          height: 100%;
          border-radius: 8px;
          object-fit: cover;
        }
        .notice-bar {
          background: #fff;
          height: 48px;
          border-bottom-left-radius: 8px;
          border-bottom-right-radius: 8px;
          display: flex;
          align-items: center;
          padding: 0 16px;
          gap: 12px;
          cursor: pointer;

          .notice-icon {
            width: 24px;
            height: 24px;
            flex-shrink: 0;
          }

          .notice-content {
            flex: 1;
            overflow: hidden;
            position: relative;

            .notice-text {
              white-space: nowrap;
              font-family: PingFang SC;
              font-size: 16px;
              font-weight: 400;
              color: #333333;
              display: inline-block;

              &.scroll-animation {
                animation: scroll-left 15s linear infinite;
              }
            }
          }
        }
      }
    }
    .service,
    .map {
      width: 100%;
      border-radius: 8px;
      .item {
        cursor: pointer;
        width: 207px;
        height: 88px;
        border-radius: 16px;
        background:
          linear-gradient(92.93deg, #b9eff6 2.44%, #ddf7fb 51.14%),
          linear-gradient(180deg, rgba(185, 239, 246, 0) 0%, #b9eff6 100%);
        background-repeat: no-repeat;
        background-size: contain;
      }
      .service-list,
      .map-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
      }
      .header {
        width: 153px;
        height: 31px;
        margin-bottom: 8px;
      }
    }
  }
  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    color: #94979c;
    font-family: PingFang SC;
    font-weight: 400;
    font-style: Regular;
    font-size: 14px;
    text-align: center;
    padding: 14px 0;
    border-top: 2px solid #0000000d;
  }
}

@keyframes scroll-left {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}
</style>
